package com.cms.clash.util;

import com.cms.clash.dto.ArcShowDTO;
import com.cms.clash.entity.HostEntity;
import com.cms.clash.service.impl.ArchiveService;
import com.cms.clash.service.impl.HostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * CacheHandler
 * @author cms
 * @date 2024-07-28
*/
@Component
public class CacheUtils {

    @Autowired
    private HostService hostService;

    @Autowired
    private ArchiveService archiveService;

    /**
     * 获取热门主机缓存
     * @param num
     * @return
     */
    public List<HostEntity> getHostList(Integer num) {
        String keyStr = "getHostList_" + num;
        Object ifPresent = TemplateUtil.cache.getIfPresent(keyStr);
        if (ifPresent != null) {
            return (List<HostEntity>) ifPresent;
        } else {
            List<HostEntity> hostList = hostService.getHostList(num);
            TemplateUtil.cache.put(keyStr, hostList);
            return hostList;
        }
    }

    /**
     * 缓存文档查询
     * @param typeId
     * @param limitNum
     * @param flag
     * @param orderBy
     * @return
     */
    public List<ArcShowDTO> getArcList(Integer typeId, Integer limitNum, String flag, String orderBy) {
        String key = "getArcList_" + typeId + "_" + flag + "_" + limitNum + "_" + orderBy;
        Object ifPresent = TemplateUtil.cache.getIfPresent(key);
        if (ifPresent != null) {
            return (List<ArcShowDTO>) ifPresent;
        } else {
            List<ArcShowDTO> entityList = archiveService.getArcList(typeId, limitNum, flag, orderBy);
            TemplateUtil.cache.put(key, entityList);
            return entityList;
        }
    }

    /**
     * 获取分类总数缓存
     * @param typeId
     * @param flag
     * @param keyWord
     * @return
     */
    public Integer queryArcListSearchCount(Integer typeId, String flag, String keyWord) {
        String keyStr = "queryArcListSearchCount_" + typeId + "_" + flag + "_" + keyWord;
        Object ifPresent = TemplateUtil.cache.getIfPresent(keyStr);
        if (null != ifPresent) {
            return (Integer) ifPresent;
        } else {
            Integer total = archiveService.queryArcListSearchCount(typeId, flag, keyWord);
            TemplateUtil.cache.put(keyStr, total);
            return total;
        }
    }

}
